/**
 * Created by zaife_000 on 2014/3/28.
 */
package com.familybox.app.view.mediators {

    import com.adobe.crypto.MD5;
    import com.adobe.serializers.json.JSONDecoder;
    import com.familybox.app.events.LoginEvent;
    import com.familybox.app.model.User;
    import com.familybox.app.services.IAuthService;
    import com.familybox.app.view.components.LoginView;

    import flash.data.EncryptedLocalStore;

    import flash.net.NetworkInfo;
    import flash.net.NetworkInterface;
    import flash.utils.ByteArray;

    import mx.utils.ObjectProxy;

    import org.robotlegs.mvcs.Mediator;
    import org.robotlegs.oil.async.Promise;
    import org.robotlegs.oil.rest.JSONClient;

    public class LoginMediator extends Mediator {

        [Inject]
        public var loginView:LoginView;

        [Inject]
        public var authService:IAuthService;

        override public function onRegister():void {
            eventMap.mapListener(loginView, LoginEvent.LOGIN_SUBMITTED, onLoginSubmitted);
        }

        private function onLoginSubmitted(e:LoginEvent):void {

            //loginView.loginBtn.label="登陆中...";

            var password:String=MD5.hash(loginView.passwordTxt.text);

            var result:Promise = authService.login(loginView.usernameTxt.text, password);

            result.addResultHandler(handler)
                    .addErrorHandler(handler)
                    .addProgressHandler(handler);
        }

        private function handler(p:Promise):void {

            if(p.status==Promise.COMPLETE){
                trace(p.result);
                var result:Object=p.result;

                var data:Object=result.data;

                if(data.success==true){
                    //EncryptedLocalStore.setItem('token',data.token);

                    var tokenBytes:ByteArray = new ByteArray();
                    tokenBytes.writeUTFBytes(data.token);
                    EncryptedLocalStore.setItem('token', tokenBytes);
                    //EncryptedLocalStore.removeItem(userid.text);
                }

                trace(data.token);

            }

//            trace(p.status);
//            trace(p.result);
//            trace(p.error);
//            trace(p.progress);
        }
    }
}
